package com.tabjin.rfidsocket.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author tabjin
 * create at 2020/11/12 22:40
 * @program rfid_socket
 * @description
 */
@Component
public class AppServer {

    final static Logger logger = LoggerFactory.getLogger(AppServer.class);

    private static class SingletionAppServer {
        static final AppServer instance = new AppServer();
    }

    public static AppServer getInstance() {
        return SingletionAppServer.instance;// 保证AppServer是以单例形式获取
    }

    private int port = 18080;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap server;
    private ChannelFuture future;


    public AppServer() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ServerInitializer());
    }

    public void start() {
        this.future = server.bind();//这边由于不是在main方法中，不需要sync
        System.err.println("服务端启动完毕");
        logger.info("服务端启动完毕");
        // 资源释放就不要了，SpringBoot容器就可以完成释放
    }


//    public void run() throws InterruptedException {
//        EventLoopGroup bossGroup = new NioEventLoopGroup();
//        EventLoopGroup workerGroup = new NioEventLoopGroup();
//
//        try {
//            server = new ServerBootstrap();
//            server.group(bossGroup, workerGroup)
//                    .channel(NioServerSocketChannel.class)
//                    .localAddress(new InetSocketAddress(port))
//                    .childHandler(new ServerInitializer());
//
//            ChannelFuture future = server.bind().sync();
//
//            future.channel().closeFuture().sync();
//        } finally {
//            bossGroup.shutdownGracefully().sync();
//            workerGroup.shutdownGracefully().sync();
//        }
//    }
//
//    public static void main(String[] args) throws InterruptedException {
//        new AppServer(18080).run();
//    }
}
